package com.example.demofdfs.aop;

import java.lang.reflect.Method;

import javax.annotation.Resource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.example.demofdfs.model.UserLog;
import com.example.demofdfs.service.UserLogService;

@Component
public class UserLogContext implements LogContext {
	
	@Autowired
	private UserLogService logService;
	
//	@Resource(name = "addLogState")
	private LogState addLogState;
//	@Resource(name = "updateLogState")
	private LogState updateLogState;
//	@Resource(name = "deleteLogState")
	private LogState deleteLogState;
//	@Resource(name = "getLogState")
	private LogState getLogState;
//	@Resource(name = "unknownLogState")
	private LogState unknownLogState;
	
	
	@Override
	public Object request(ProceedingJoinPoint point) throws Throwable {

		LogState state;
		LogAnnotation anno = this.getAnno(point);
		state = this.getState(anno);
		
		return state.handle(point);
	}

	public LogState getState(LogAnnotation anno) {
		LogOperateEnum[] method;
		if (anno == null || (method = anno.value()).length == 0)
			return unknownLogState;
			
		String oName = method[0].name();
		if (oName.equals("ADD"))
//			return new AddLogState(this);
			return addLogState;
		else if ("GET".equals(oName))
//			return new GetLogState(this);
			return getLogState;
		else if ("UPDATE".equals(oName))
//			return new UpdateLogState(this);
			return updateLogState;
		else if ("DELETE".equals(oName))
//			return new DeleteLogState(this);
			return deleteLogState;
		
		return unknownLogState;
//		return new UnknownLogState();
		
	}
	
	private LogAnnotation getAnno(ProceedingJoinPoint point) throws NoSuchMethodException, SecurityException {
		Signature sig = point.getSignature();
		MethodSignature msig = null;
		if (!(sig instanceof MethodSignature)) {
			throw new IllegalArgumentException("该注解只能用于方法");
		}
		msig = (MethodSignature) sig;
		Object target = point.getTarget();
		Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
		
		return currentMethod.getAnnotation(LogAnnotation.class);
	}

	@Override
	public int insertLog(UserLog log) {
//		System.out.println("正在写入日志..." + log.getMsg());
		return logService.insert(log);
	}
}
